<?php

class AdminController extends BackendController
{
    public function filters()
    {
        $parent_filters = parent::filters();
        // $parent_filters[] = 'filterFunction';
        return $parent_filters;
    }

    public function actionAdminLock()
    {
        $id = Yii::app()->request->getQuery('id');
        if ((isset($id)) AND ($id !== '')) {
            if (!is_numeric($id)) {
                echo 'хак'; exit;
            }
            $admin_model = new BackendAdmin();
            $admin_model->lock($id);
        }
        $this->redirect($this->createUrl('Admin/AdminList'));
    }

    public function actionAdminEdit()
    {
        $this->pageTitle = Yii::t('admin_edit', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $id = Yii::app()->request->getQuery('id');
        if ((isset($id)) AND ($id !== '')) {
            if (!is_numeric($id)) {
                echo 'хак'; exit;
            }
            $arr = array();
            $admin_model = new BackendAdmin();
            $admin = $admin_model->getAdminOne($id);
            foreach ($admin as $val) {
                $arr = array ('id' => $val['id'], 'email' => $val['email'], 'role' => $val['itemname']);
            }
            $role_model = new BackendAdmin();
            $role = $role_model->getRole();
            $list = CHtml::listData($role, 'name', 'name');
            $rf = new BackendAdminForm('admin_edit');
            if (Yii::app()->request->getPost('BackendAdminForm') !== null)
            {
                $rf->attributes = Yii::app()->request->getPost('BackendAdminForm');
                if ($rf->validate())
                {
                    $admin_model->edit($rf->email, $rf->password, $rf->role, $arr['role'], $id);
                    $this->redirect($this->createUrl('Admin/AdminList'));
                }
            }
        }
        $this->render('edit', array('form' => $rf, 'row' => $arr, 'list' => $list));
    }

    public function actionAdminDel()
    {
        $role = Yii::app()->request->getQuery('role');
        $id = Yii::app()->request->getQuery('id');
        $role = strtolower($role);
        if ((isset($role, $id)) AND ($role !== '') AND ($id !== '')) {
            if (!is_numeric($id)) {
                echo 'хак'; exit;
            }

            $admin_model = new BackendAdmin();
            $admin_model->del($id, $role);
        }
        $this->redirect($this->createUrl('Admin/AdminList'));
    }

    public function actionAdminAdd()
    {
        $this->pageTitle = Yii::t('admin_add', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $role_model = new BackendAdmin();
        $role = $role_model->getRole();
        $list = CHtml::listData($role, 'name', 'name');

        $rf = new BackendAdminForm('admin_add');

        if (Yii::app()->request->getPost('BackendAdminForm') !== null)
        {
            $rf->attributes = Yii::app()->request->getPost('BackendAdminForm');
            if ($rf->validate())
            {
                $admin_model = new BackendAdmin();
                $tmp = $admin_model->isExists($rf->email, $rf->password);
                if ($tmp == false) {
                    $admin_model->add($rf->email, $rf->password, $rf->role);
                    $this->redirect($this->createUrl('Admin/AdminList'));
                } else {
                    $rf->addError('email', 'Пользователь с таким email уже зарегистрирован!');
                }
            }
        }
        $row = array('email' => '', 'password' => '', 'role' => 'Nobody');
        $this->render('add', array('form' => $rf, 'row' => $row, 'list' => $list));
    }

    public function actionAdminList()
    {
        $this->pageTitle = Yii::t('admin_list', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $admin_model = new BackendAdmin();
        $row = $admin_model->getAdminList()->readAll();

        foreach ($row as $val) {
            if ($val['status'] == 1) {
                $val['status'] = '<span style="color:red;">[разблокировать]</span>';
            } else {
                $val['status'] = '[заблокировать]';
            }
            $arr[] = array('status' => $val['status'], 'id' => $val['id'], 'name' => $val['itemname'], 'email' => $val['email']);
        }

        if ($arr) {
            $dataProvider = new CArrayDataProvider($arr,array('pagination' => array(
                    'pagesize' => 15,
                ),));
        } else {
            $dataProvider = new CArrayDataProvider(array());
        }

        $this->render('list', array('dataProvider' => $dataProvider));
    }

    public function actionAdminGroup()
    {
        $this->pageTitle = Yii::t('admin_group', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $admin_model = new BackendAdmin();
        $row = $admin_model->getAdminGroupList();

        $this->render('group', array('row' => $row));
    }

    public function actionAdminGroupAdd()
    {
        $this->pageTitle = Yii::t('admin_group_add', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';

        /*---*/
        $child_model = new BackendAdmin();
        $ch = $child_model->getChild();
        $role_array = array();
        foreach($ch as $value)
        {
            if (preg_match("/^([^\/]+)/i", $value['name'], $result)) {
                $role_array[$result[0]][]=$value;
            }
        }
        $list = array();
        foreach($role_array as $key=>$value)
        {
            $list[$key] = CHtml::listData($value, 'name', 'description');
        }
        /*---*/

        $rf = new BackendAdminForm('group_add');
        if (Yii::app()->request->getPost('BackendAdminForm') !== null)
        {
            $attributes = Yii::app()->request->getPost('BackendAdminForm');
            $attributes['child'] = Yii::app()->request->getPost('child');
            $rf->attributes = $attributes;
            if ($rf->validate())
            {
                $tmp = Yii::app()->authManager->getAuthItem($rf->role);
                if ($tmp == NULL) {
                    $role = Yii::app()->authManager->createRole($rf->role);
                    foreach ($rf->child as $val) {
                        $role->addChild($val);
                    }
                    $this->redirect($this->createUrl('Admin/AdminGroup'));
                } else {
                    $rf->addError('email', 'Группа с таким именем уже сущевствует!');
                }
            }
        }
        $row = array('role' => '');
        $this->render('group_add', array('form' => $rf, 'row' => $row, 'list' => $list));
    }

    public function actionAdminGroupEdit()
    {
        $this->pageTitle = Yii::t('admin_group_edit', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';
        $role = Yii::app()->request->getQuery('role');
        $role = strtolower($role);
        if ((isset($role)) AND ($role !== '')) {
            $child_model = new BackendAdmin();
            $ch = $child_model->getChild();
            $role_array = array();
            foreach($ch as $value)
            {
                if (preg_match("/^([^\/]+)/i", $value['name'], $result)) {
                    $role_array[$result[0]][]=$value;
                }
            }
            $role_list = array();
            foreach($role_array as $key=>$value)
            {
                $role_list[$key] = CHtml::listData($value, 'name', 'description');
            }

            //$list = CHtml::listData($ch, 'name', 'description');

            $select = $child_model->getChildByRole($role);
            foreach ($select as $v) {
                $arr_sel[] = $v['child'];
            }

            $rf = new BackendAdminForm('group_edit');
            if (Yii::app()->request->getPost('BackendAdminForm') !== null)
            {
                $attributes = Yii::app()->request->getPost('BackendAdminForm');
                $attributes['child'] = Yii::app()->request->getPost('child');
                $rf->attributes = $attributes;
                if ($rf->validate())
                {
                    $child = Yii::app()->request->getPost('child');
                    $rf->role = strtolower($rf->role);
                    $error = false;
                    if (!($rf->role === $role)) {
                        $tmp = Yii::app()->authManager->getAuthItem($rf->role);
                        if ($tmp !== NULL) {
                            $error = true;
                        } else {
                            $error = false;
                        }
                    }

                    if (!$error) {
                        if (isset($child)) {
                            $authItem = new CAuthItem(Yii::app()->authManager, $rf->role, CAuthItem::TYPE_ROLE);
                            Yii::app()->authManager->saveAuthItem($authItem, $role);
                            foreach ($arr_sel as $val) {
                                Yii::app()->authManager->removeItemChild($rf->role, $val);
                            }
                            foreach ($child as $val) {
                                $authItem->addChild($val);
                            }
                            $this->redirect($this->createUrl('Admin/AdminGroup'));
                        } else {
                            $rf->addError('role', 'Необходимо выбрать права!');
                        }
                    } else {
                        $rf->addError('role', 'Группа с таким именем уже сущевствует!');
                    }
                }
            }
        }
        $this->render('group_edit', array('form' => $rf, 'role' => $role, 'list' => $role_list, 'select' => $arr_sel));
    }

    public function actionAdminGroupDel()
    {
        $role = Yii::app()->request->getQuery('role');
        $role = strtolower($role);
        if ((isset($role)) AND ($role !== '')) {
            $admin_model = new BackendAdmin();
            $arr_admin = $admin_model->getAdminList();
            foreach ($arr_admin as $val) {
                $tmp = Yii::app()->authManager->getAuthAssignment($role, $val['userid']);
                if ($tmp !== NULL) {
                    echo 'К данной группе, привязан пользователь '.$val['email'].'! Удалять нельзя!'; exit;
                }
            }
            $select = $admin_model->getChildByRole($role);
            foreach ($select as $v) {
                Yii::app()->authManager->removeItemChild($role, $v['child']);
            }
            Yii::app()->authManager->removeAuthItem($role);
            $this->redirect($this->createUrl('Admin/AdminGroup'));
        }
    }
    public function actionAdminAction()
    {
        $this->pageTitle = Yii::t('admin_action', 'PAGE_TITLE');
        $this->pageKeywords = '';
        $this->pageDescription = '';

        $admin_id = Yii::app()->request->getQuery('id');
        $admin_model = new BackendAdminAction();
        if ((isset($admin_id)) AND ($admin_id !== '')) {
            if (!is_numeric($admin_id)) {
                echo 'хак'; exit;
            }
            $row = $admin_model->getActionOne($admin_id);
        } else {
            $row = $admin_model->getAction();
        }
        $row = $row->readAll();
        if ($row) {
            $dataProvider = new CArrayDataProvider($row,array('pagination' => array(
                    'pagesize' => 15,
                ),));
        } else {
            $dataProvider = new CArrayDataProvider(array());
        }

        $this->render('action', array('dataProvider' => $dataProvider));
    }

}
